package com.lagou.rpc.api.impl;

import com.lagou.rpc.common.RequestMetrics;

import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @param
 * @author oyz
 * @version 1.0
 * @description: TODO 最小负载策略
 * @date 2022/3/1 11:39
 */
public class MinCostLoadBalance extends AbstractLoadBalance {


    @Override
    protected String doSelect(List<String> address) {
        if(address.isEmpty()){
            return null;
        }
        String connectString = "";
        List<String> collect = null;
        // ip  port  cost
        List<RequestMetrics.Metries> allInstances = RequestMetrics.getInstance().getAllInstances();
        if (allInstances.isEmpty()){
            // 使用随机策略
            connectString = new RandomLoadBalance().doSelect(address);
        }
        // 请求记录数没有实际的注册数目多,说明负载还没有轮完,无法按照最少时间的机器转发
        if(allInstances.size()<address.size()){
            // 继续随机
            connectString = new RandomLoadBalance().doSelect(address);
        }else {
            // 所有请求都被轮询了一遍
            Collections.sort(allInstances, new Comparator<RequestMetrics.Metries>() {
                @Override
                public int compare(RequestMetrics.Metries o1, RequestMetrics.Metries o2) {
                    return Long.compare(o1.getCost(),o2.getCost());
                }
            });
            // 获取花费时间最少的服务器
            RequestMetrics.Metries metries = allInstances.get(0);
            collect = address.stream().filter(String -> String.equals(metries.getIp() + ":" + metries.getPort())).collect(Collectors.toList());

        }

        return collect.get(0);
    }
}
